"""
@Time    : 2019/10/26 17:38
@Author  : CcH
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
from functools import partial
import torch.nn.init as init
from AttentionModel.self_attention import SelfAttentionDot

__all__ = [
    'ResNet', 'resnet10', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
    'resnet152', 'resnet200'
]


def conv3x3x3(in_planes, out_planes, stride=1):
    # 3x3x3 convolution with padding
    return nn.Conv3d(
        in_planes,
        out_planes,
        kernel_size=3,
        stride=stride,
        padding=1,
        bias=False)


def downsample_basic_block(x, planes, stride):
    out = F.avg_pool3d(x, kernel_size=1, stride=stride)
    zero_pads = torch.Tensor(
        out.size(0), planes - out.size(1), out.size(2), out.size(3),
        out.size(4)).zero_()
    if isinstance(out.data, torch.cuda.FloatTensor):
        zero_pads = zero_pads.cuda()

    out = Variable(torch.cat([out.data, zero_pads], dim=1))

    return out


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm3d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3x3(planes, planes)
        self.bn2 = nn.BatchNorm3d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm3d(planes)
        self.conv2 = nn.Conv3d(
            planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn2 = nn.BatchNorm3d(planes)
        self.conv3 = nn.Conv3d(planes, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm3d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class ResNet(nn.Module):

    def __init__(self,
                 block,
                 layers,
                 shortcut_type='B',
                 num_classes=313):
        self.inplanes = 32
        super(ResNet, self).__init__()
        self.conv1 = nn.Conv3d(
            1,
            32,
            kernel_size=(3, 5, 5),
            stride=(1, 2, 2),
            padding=(1, 2, 2),
            bias=False)
        self.bn1 = nn.BatchNorm3d(32)
        self.relu = nn.ReLU(inplace=True)
        # self.maxpool = nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1,2,2), padding=(0, 1, 1))
        self.maxpool = nn.MaxPool3d(kernel_size=(1, 2, 2), stride=(1, 2, 2), padding=(0, 1, 0))
        self.layer1 = self._make_layer(block, 32, layers[0], shortcut_type)
        self.layer2 = self._make_layer(
            block, 64, layers[1], shortcut_type, stride=(1,2,2))
        self.layer3 = self._make_layer(
            block, 96, layers[2], shortcut_type, stride=(1,2,2))
        # self.layer4 = self._make_layer(
        #     block, 256, layers[3], shortcut_type, stride=(1,2,2))
        self.maxpool_out = nn.MaxPool3d(kernel_size=(1, 2, 2), stride=(1, 2, 2),padding=(0,0,1))
        self.pred = nn.Linear(512*2, num_classes)
        self.gru1 = nn.GRU(96 * 2 * 4, 256, bidirectional=True, batch_first=True)
        self.drp1 = nn.Dropout(0.5)
        # T B F
        self.attention = SelfAttentionDot(512, 512)
        self.gru2 = nn.GRU(512, 256, 1, bidirectional=True, batch_first=True)
        self.drp2 = nn.Dropout(0.5)

        self.bn_norm1 = nn.BatchNorm1d(512, momentum=0.5)

        for m in self.modules():
            if isinstance(m, nn.Conv3d):
                m.weight = nn.init.kaiming_normal_(m.weight, mode='fan_out')
            elif isinstance(m, nn.BatchNorm3d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

        for m in (self.gru1,self.gru2):
            stdv = math.sqrt(2 / (96 * 2 * 4 + 256))
            for i in range(0, 256 * 3, 256):
                init.uniform_(m.weight_ih_l0[i: i + 256],
                              -math.sqrt(3) * stdv, math.sqrt(3) * stdv)
                init.orthogonal_(m.weight_hh_l0[i: i + 256])
                init.constant_(m.bias_ih_l0[i: i + 256], 0)
                init.uniform_(m.weight_ih_l0_reverse[i: i + 256],
                              -math.sqrt(3) * stdv, math.sqrt(3) * stdv)
                init.orthogonal_(m.weight_hh_l0_reverse[i: i + 256])
                init.constant_(m.bias_ih_l0_reverse[i: i + 256], 0)



    def _make_layer(self, block, planes, blocks, shortcut_type, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            if shortcut_type == 'A':
                downsample = partial(
                    downsample_basic_block,
                    planes=planes * block.expansion,
                    stride=stride)
            else:
                downsample = nn.Sequential(
                    nn.Conv3d(
                        self.inplanes,
                        planes * block.expansion,
                        kernel_size=1,
                        stride=stride,
                        bias=False), nn.BatchNorm3d(planes * block.expansion),nn.ReLU(True))

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        # x = self.layer4(x)

        x = self.maxpool_out(x)

        x = x.permute(0, 2, 1, 3, 4).contiguous()

        x = x.view(x.size(0), x.size(1), -1)
        x, hidden = self.gru1(x)
        x = self.drp1(x)

        x, _ = self.gru2(x,hidden)

        x = x.contiguous()
        x = x.view(-1, 512)
        x = self.bn_norm1(x)
        x = x.view(-1, 20, 512)

        att_out = self.attention(x)
        pool_out = x.transpose(1, 2)
        pool_out = F.max_pool1d(pool_out, pool_out.size(2)).squeeze(2)
        out = torch.cat((att_out, pool_out), dim=1)

        out = self.drp2(out)
        out = self.pred(out).log_softmax(-1)

        return out

class LipSeqLoss(nn.Module):
    def __init__(self):
        super(LipSeqLoss, self).__init__()
        self.criterion = nn.NLLLoss(reduction='none')

    def forward(self, input, length, target):
        loss = []
        transposed = input.transpose(0, 1).contiguous()
        # transposed = input
        for i in range(transposed.size(0)):
            loss.append(self.criterion(transposed[i,], target.squeeze(1)).unsqueeze(1))
        loss = torch.cat(loss, 1)

        # GPU version
        mask = torch.zeros(loss.size(0), loss.size(1)).float().cuda()
        # Cpu version
        #         mask = torch.zeros(loss.size(0), loss.size(1)).float()

        for i in range(length.size(0)):
            L = min(mask.size(1), length[i])
            mask[i, L - 1] = 1.0
        loss = (loss * mask).sum() / mask.sum()
        return loss


def resnet10(**kwargs):
    """Constructs a ResNet-18 model.
    """
    model = ResNet(BasicBlock, [1, 1, 1, 1], **kwargs)
    return model


def resnet18(**kwargs):
    """Constructs a ResNet-18 model.
    """
    model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
    return model


def resnet34(**kwargs):
    """Constructs a ResNet-34 model.
    """
    model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
    return model


def resnet50(**kwargs):
    """Constructs a ResNet-50 model.
    """
    model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
    return model



if __name__ == '__main__':
    from DataLoader.Picture_Process import file_2_allpicture

    path = r"D:\XW_Bank\LipRecognition\train\lip_100_50_train\000c43e99bdceb93a39e729ffc38ac2a"
    input_p, pct_len = file_2_allpicture(path)
    model = resnet10(num_classes = 313).cuda()
    basicblock = BasicBlock(1,64).cuda()
    bottleneck = Bottleneck(1,64).cuda()
    src = input_p.cuda()
    output = model(src)
    print(output.shape)
    length = torch.LongTensor([9]).cuda()
    print()